package com.h3bpm.web.ext.controller;

import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.ViewModels.ActionResult;
import OThinker.H3.Controller.ViewModels.Item;
import OThinker.H3.Entity.Acl.FunctionNode;
import OThinker.H3.Entity.IEngine;
import OThinker.H3.Entity.Instance.Data.IInstanceDataItem;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctc.wstx.io.CharsetNames;
import com.h3bpm.base.res.ResBody;
import com.h3bpm.base.user.UserValidator;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.web.util.DBUtil;
import data.DataRow;
import data.DataTable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gaoqiang
 * @date 2022/1/26
 */
@Slf4j
@RestController
@RequestMapping("/userPortal")
public class UserPortalController extends ControllerBase {

    @Override
    public String getFunctionCode()
    {
        return FunctionNode.ProcessModel_BizMasterData_Code;
    }

    @PostMapping("/selectUser")
    public final List<Map<String, Object>> GetGridData(String userCode,String emp_number,String emp_name,String dept_name,String emp_personneltype,String emp_incumbencystate,String emp_mobilephone) throws Exception {
        if(ObjectUtils.anyNotNull(userCode)){
            long a1 = System.currentTimeMillis();
            Connection con = DBUtil.getConnection();
            long a5 = System.currentTimeMillis();
            CallableStatement callStatement = con.prepareCall("{CALL HR_Person_Data_Permission(?)}");
            callStatement.setString(1, userCode);
            ResultSet resultSet = callStatement.executeQuery();
            long a2 = System.currentTimeMillis();
            List<Map<String, Object>> lists = convertList(resultSet);
            long a3 = System.currentTimeMillis();
            log.info("size:{}",lists.size());
            lists = getList(lists,emp_number,"emp_number");
            lists = getList(lists,emp_name,"emp_name");
            lists = getList(lists,dept_name,"dept_name");
            lists = getList(lists,emp_personneltype,"emp_personneltype");
            lists = getList(lists,emp_incumbencystate,"emp_incumbencystate");
            lists = getList(lists,emp_mobilephone,"emp_mobilephone");
            callStatement.close();
            con.close();
            long a4 = System.currentTimeMillis();
            log.info("a1-a2共耗时：" + ((a2 - a1) / 1000.0) + "秒");
            log.info("a2-a3共耗时：" + ((a3 - a2) / 1000.0) + "秒");
            log.info("a3-a4共耗时：" + ((a4 - a3) / 1000.0) + "秒");
            log.info("a1-a4共耗时：" + ((a4 - a1) / 1000.0) + "秒");
            log.info("a1-a5共耗时：" + ((a5 - a1) / 1000.0) + "秒");
            return lists;
        }else {
            return new ArrayList<>();
        }
    }
    @PostMapping("/selectUserTest")
    public final void selectUser(String userCode) throws Exception {
        //1.加载驱动程序
        Class.forName("com.mysql.jdbc.Driver");
        //2. 获得数据库连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/h3bpm2", "root", "root");
        //3.操作数据库，实现增删改查
        Statement stmt = conn.createStatement();
        String sqlStr = "select Describes from i_ywgl_xtbugfk  where ObjectID='b7348f17-8041-4ea5-8798-262916a6faf6'";
        ResultSet rs = stmt.executeQuery(sqlStr);
        //如果有数据，rs.next()返回true
        String note ="";
        while(rs.next()){
            InputStream is = null;
            ByteArrayInputStream bais = null;
            ObjectInputStream ojb = null;
            Object result = null;
            try{
                is = rs.getBlob(1).getBinaryStream();
                bais = (ByteArrayInputStream)is;
                ojb = new ObjectInputStream(bais);
                result = ojb.readObject();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                is.close();
                ojb.close();
            }
        }
    }
    @PostMapping("/selectUserExt")
    public final List<Map<String, Object>> GetGridDataExtend(String userCode,String emp_number,String emp_name,String dept_name,String emp_personneltype,String emp_incumbencystate,String emp_mobilephone) throws Exception {
        IEngine engine = AppUtility.getEngine();
        Connection con = DBUtil.getConnection();
        String sqlStr = "SELECT objectid,code FROM OT_USER WHERE STATE='1' ";
        DataTable InstanceTable = getEngine().getEngineConfig().
                getCommandFactory().CreateCommand().ExecuteDataTable(sqlStr);
        Map<String,String> userMap = new HashMap<String,String>();
        if (InstanceTable != null && InstanceTable.getRows().size() > 0) {
            //一次获取所有用户
            for (int i = 0; i < InstanceTable.getRows().size(); i++) {
                DataRow row = InstanceTable.getRows().get(i);
                userMap.put(row.getString("code"),row.getString("objectid"));
            }
        }
        if(ObjectUtils.anyNotNull(userCode)){
            CallableStatement callStatement = con.prepareCall("{CALL HR_Person_Data_Permission(?)}");
            callStatement.setString(1, userCode);
            ResultSet resultSet = callStatement.executeQuery();
            List<Map<String, Object>> lists = convertList(resultSet);
            lists = lists.stream().filter(e -> ObjectUtils.anyNotNull(userMap.get(e.get("emp_number")))).collect(Collectors.toList());
            lists.stream().forEach(e ->e.put("empid",userMap.get(e.get("emp_number"))));
            log.info("size:{}",lists.size());
            lists = getList(lists,emp_number,"emp_number");
            lists = getList(lists,emp_name,"emp_name");
            lists = getList(lists,dept_name,"dept_name");
            lists = getList(lists,emp_personneltype,"emp_personneltype");
            lists = getList(lists,emp_incumbencystate,"emp_incumbencystate");
            lists = getList(lists,emp_mobilephone,"emp_mobilephone");

            log.info("size:{}",lists.size());
            callStatement.close();
            con.close();
            return lists;
        }else {
            engine.getLogWriter().Write("当前登录用户无法查询外部信息" );
            return new ArrayList<>();
        }
    }

    private static List<Map<String, Object>> convertList(ResultSet rs) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();
        while (rs.next()) {
            Map rowData = new HashMap();
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnName(i), rs.getObject(i));
            }
            list.add(rowData);
        }
        return list;
    }
    private  List<Map<String, Object>> getList (List<Map<String, Object>> lists ,String value,String name){
        if(StringUtils.isNotEmpty(value)&&!((name+", ShortString").equals(value))){
            lists = lists.stream().filter(e -> ((String)e.get(name)).contains(value)).collect(Collectors.toList());
        }
        return lists;
    }
}
